package cn.faster.config.minio;

import io.minio.MinioClient;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * description: MinioConfig 暂时没用到
 * date: 2021/6/18 11:26
 * author: XiaoCoder
 * version: 1.0
 */
@Component
@PropertySource("classpath:application-dev.yml")
@ConfigurationProperties(prefix = "minio")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MinioConfig {

    @Value("${url}")
    private String url;

    @Value("${accessKey}")
    private String accessKey;

    @Value("${secretKey}")
    private String secretKey;

    @Value("${buckName}")
    private String buckName;

    public MinioClient getMinioClient() throws Exception {
        return new MinioClient(url, accessKey, secretKey);
    }

    /**
     * 上传图片返回图片数据信息
     *
     * @param file
     * @return Map<String, String>
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> upload(MultipartFile file) throws Exception {
        if (!file.isEmpty()){
            InputStream inputStream = file.getInputStream();// 得到文件流
            String contentType = file.getContentType();// 文件类型
            // 截断后缀信息
            int i = contentType != null ? contentType.indexOf("/") : 0;
            contentType= Objects.requireNonNull(contentType).substring(i+1);
            // 创建新名字
            String uuid = UUID.randomUUID().toString().replace("-", ""); //转换uuid信息
            String name = uuid+"."+ contentType; //文件名字
            getMinioClient().putObject(buckName, name, inputStream, contentType);
            HashMap<String, String> imageInfoMap = new HashMap<>();
            imageInfoMap.put("uuid", uuid);
            imageInfoMap.put("name", name);
            imageInfoMap.put("contentType", contentType);
            imageInfoMap.put("buckName", buckName);
            return imageInfoMap;
        }
        throw new NullPointerException();

    }
    @Transactional(rollbackFor = Exception.class)
    public String remove(String imgName) throws Exception{
        getMinioClient().removeObject(buckName,imgName);
        return imgName;
    }


}
